package my.music.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import my.music.interceptor.CorsInterceptor;
import my.music.interceptor.IdempotentInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Resource
    private CorsInterceptor corsInterceptor;
    @Resource
    private IdempotentInterceptor idempotentInterceptor;

    // 注册Sa-Token的注解拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 跨域拦截器
        registry.addInterceptor(corsInterceptor).addPathPatterns("/**");

        registry.addInterceptor(idempotentInterceptor).addPathPatterns("/**");

        // 注册路由拦截器，自定义认证规则
        registry.addInterceptor(new SaInterceptor(handle -> {
            // 登录认证 -- 拦截所有路由
            SaRouter.match("/**/api/**", r -> StpUtil.checkLogin());
            // 检查当前会话是否已通过二级认证，如未通过则抛出异常
            SaRouter.match("/**/api/safe/**", r -> StpUtil.checkSafe());

            // 角色
            SaRouter.match("/**/api/system/**", r -> StpUtil.checkPermission("system"));
        })).addPathPatterns("/**");
    }
}
